<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务" prop="taskId">
        <!-- <el-input v-model="queryParams.taskId" placeholder="请输入任务序号" clearable @keyup.enter="handleQuery"/> -->
         <el-select v-model="queryParams.taskName" placeholder="请选择任务" clearable filterable @change="handleQuery" style="width: 240px;">
          <el-option v-for="item in uniqueTaskNameOptions" :key="item.taskName" :label="item.taskName" :value="item.taskName" :title="item.taskName"/>
        </el-select>
      </el-form-item>
      <el-form-item label="采集人" prop="collectorId">
        <el-select  v-model="queryParams.collectorId" placeholder="请选择采集人" clearable filterable @change="handleQuery" style="width: 240px;">
          <el-option v-for="item in userOptions" :key="item.userId" :label="getUserLabel(item)" :value="item.userId" :title="getUserLabel(item)"/>
        </el-select>
      </el-form-item>
      <el-form-item label="采集时间" prop="collectTime">
        <el-date-picker clearable v-model="queryParams.collectTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择采集时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['peach:record:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['peach:record:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['peach:record:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
      <el-button type="warning" plain icon="Download" :disabled="multiple || !hasSelectValidImages" @click="handleExport" v-hasPermi="['peach:record:export']">导出</el-button>
    </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="displayRecordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="recordId" />
      <el-table-column label="任务" align="center" prop="taskName" />
      <el-table-column label="采集人" align="center" prop="collectorName" />
      <el-table-column label="采集时间" align="center" prop="collectTime">
        <template #default="scope">
          <span>{{ parseTime(scope.row.collectTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采集值" align="center" prop="dataValue">
        <template #default="scope">
          <span v-if="scope.row.dataValue && scope.row.dataValue.trim() !== ''">
            {{ scope.row.dataValue }}
          </span>
          <span v-else style="color: #909399;">--</span>
        </template>
      </el-table-column>
      <el-table-column label="采集图片" align="center" prop="imageUrls">
        <template #default="scope">
          <image-preview :src="scope.row.imageUrls" :width="100" :height="100"/>
        </template>
      </el-table-column>
      <el-table-column label="查看图片" align="center" prop="imageUrls">
        <template #default="scope">
          <div class="image-count-container">
            <template v-if="getImageCount(scope.row) > 0">
              <el-button v-hasPermi="['peach:record:edit']" type="primary" link size="small"@click="handleViewAllImages(scope.row)">
                共 {{ getImageCount(scope.row) }} 张
              </el-button>
            </template>
            <template v-else>
              <span style="color: #909399; font-size: 12px;">暂无图片</span>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList"
    />

    <!-- 添加或修改采集记录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务ID" prop="taskId">
          <el-select v-model="form.taskId" placeholder="请选择采集任务" filterable clearable>
            <el-option
                v-for="item in taskOptions"
                :key="item.taskId"
                :label="getTaskLabel(item)"
                :value="item.taskId"
                :title="getTaskLabel(item)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="采集人ID" prop="collectorId">
          <el-select v-model="form.collectorId" placeholder="请选择采集人" filterable clearable>
            <el-option
                v-for="item in userOptions"
                :key="item.userId"
                :label="getUserLabel(item)"
                :value="item.userId"
                :title="getUserLabel(item)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采集时间" prop="collectTime">
          <el-date-picker clearable
            v-model="form.collectTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择采集时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采集值" prop="dataValue">
          <el-input v-model="form.dataValue" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="采集图片" prop="imageUrls">
          <image-upload v-model="form.imageUrls"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看全部图片对话框 -->
    <el-dialog 
      title="查看全部图片" 
      v-model="imageDialogVisible" 
      width="900px" 
      append-to-body
    >
      <el-form label-width="80px">
        <el-form-item label="采集时间">
          <span>{{ parseTime(currentRecordData?.collectTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </el-form-item>
        
        <el-form-item label="图片总数">
          <span>{{ currentImageUrls.length }} 张</span>
        </el-form-item>

        <el-form-item label="图片列表">
          <div v-if="currentImageUrls.length > 0">
            <el-row :gutter="20">
              <el-col 
                :span="25" 
                v-for="(imageUrl, index) in currentImageUrls" 
                :key="index"
              >          
                  <template #header>
                  </template>
                  <div>
                    <image-preview 
                      :src="imageUrl" 
                      :width="200" 
                      :height="200"
                    />
                  </div>
              </el-col>
            </el-row>
          </div>
          <el-empty v-else description="暂无图片" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="imageDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导出选项对话框 -->
    <el-dialog 
      title="选择导出内容" 
      v-model="exportDialogVisible" 
      width="400px" 
      append-to-body
    >
      <el-form :model="exportForm" ref="exportFormRef" :rules="exportRules">
        <el-alert
          title="提示"
          :description="`已选择 ${ids.length} 条记录${isSameTask && exportForm.exportType === 'images' ? '（同一任务，可合并导出）' : ''}`"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        />
        
        <el-form-item label="导出类型" prop="exportType">
          <el-radio-group v-model="exportForm.exportType">
            <el-radio label="data">
              <el-icon><Document /></el-icon>
              <span style="margin-left: 5px;">导出数据表格</span>
            </el-radio>
            <el-radio label="images">
              <el-icon><Picture /></el-icon>
              <span style="margin-left: 5px;">导出图片压缩包</span>
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item 
          v-if="exportForm.exportType === 'images'" 
          label="导出方式" 
          prop="exportMode"
        >
          <el-radio-group v-model="exportForm.exportMode">
            <el-radio label="multiple">导出为多个压缩包</el-radio>
            <el-radio label="single" :disabled="!isSameTask">
              导出为一个压缩包
              <el-tooltip 
                v-if="!isSameTask" 
                content="只有选中记录属于同一任务时才能合并导出" 
                placement="top"
              >
                <el-icon style="margin-left: 5px;"><QuestionFilled /></el-icon>
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="exportDialogVisible = false">取 消</el-button>
          <el-button 
            type="primary" 
            @click="confirmExport"
            :loading="exportLoading"
          >
            {{ exportLoading ? '导出中...' : '确认导出' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { listRecord, getRecord, delRecord, addRecord, updateRecord } from "@/api/peach/collectRecord";
import { downloadRecordImgZip,downloadRecordImgZipBatch } from "@/api/peach/recordImg.js"
import { listTask } from "@/api/peach/task.js";
import { listUser } from "@/api/system/user.js";
import { getCurrentInstance } from "vue";
import { Document, Picture } from '@element-plus/icons-vue';
const { proxy } = getCurrentInstance();
const exportLoading = ref(false);
const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const taskOptions = ref([]);
const userOptions = ref([]);
const currentRecordData = ref(null);
// 图片查看相关变量
const imageDialogVisible = ref(false);
const currentImageUrls = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: null,       // 选择的任务名 去重后
    taskIdList: null,     // 映射得到的一组 taskId，提交给后端
    taskId: null,         // 若想保留按单个 taskId 查
    collectorId: null,
    collectTime: null,
    dataValue: null,
    imageUrls: null,
  },
  rules: {
    taskId: [
      { required: true, message: "任务ID不能为空", trigger: "blur" }
    ],
    collectorId: [
      { required: true, message: "采集人ID不能为空", trigger: "blur" }
    ],
  }
});
// 导出对话框相关变量
const exportDialogVisible = ref(false);
const exportForm = reactive({
  exportType: 'data', // data: 导出数据, images: 导出图片
  exportMode: 'multiple' // multiple: 多个压缩包, single: 一个压缩包
});
const exportRules = {
  exportType: [ { required: true, message: "请选择导出类型", trigger: "change" }],
  exportMode: [{ required: true, message: "请选择导出方式", trigger: "change" }]
};

// 计算属性：判断选中记录是否都是同一个任务
const isSameTask = computed(() => {
  if (selectedRecords.value.length === 0) return false;
  const firstTaskId = selectedRecords.value[0].taskId;
  return selectedRecords.value.every(record => record.taskId === firstTaskId);
});

// 导出图片压缩包 
function exportImages() {
  exportLoading.value = true;
  // 过滤出有图片的记录（保留完整记录对象）
  const validImageRecords = selectedRecords.value
    .filter(row => getImageCount(row) > 0);
  if (validImageRecords.length === 0) {
    proxy.$modal.msgWarning("选中的记录中都没有图片，无法导出");
    exportLoading.value = false;
    return;
  }
  // 如果有部分记录没有图片，给出提示
  if (selectedNoImageCount.value > 0) {
    proxy.$modal.msgWarning(`已自动过滤 ${selectedNoImageCount.value} 条无图片记录，将导出 ${validImageRecords.length} 条有图片记录`);
  }
  // 根据导出方式选择不同的导出逻辑
  if (exportForm.exportMode === 'single') {
    // 导出为一个压缩包
    exportSingleZip(validImageRecords);
  } else {
    // 导出为多个压缩包
    exportMultipleZips(validImageRecords);
  }
}

// 合并导出一个压缩包
function exportSingleZip(validImageRecords) {
  const displayRecord = displayRecordList.value.find(
    r => r.recordId === validImageRecords[0].recordId
  );
  const taskName = displayRecord?.taskName || '未知任务';
  const recordIds = validImageRecords.map(r => r.recordId);
  console.log('开始导出合并压缩包:', { taskName, recordIds });
  downloadRecordImgZipBatch(recordIds, taskName)
    .then(() => {
      proxy.$modal.msgSuccess('成功导出合并压缩包');
    })
    .catch(err => {
      console.error('导出失败:', err);
      proxy.$modal.msgError('导出失败');
    })
    .finally(() => {
      exportLoading.value = false;
      exportDialogVisible.value = false;
    });
}

// 导出多个压缩包
function exportMultipleZips(validImageRecords) {
  const downloads = validImageRecords.map(record => {
    const displayRecord = displayRecordList.value.find(
      r => r.recordId === record.recordId
    );
    const taskName = displayRecord?.taskName || '未知任务';
    return downloadRecordImgZip(record.recordId, taskName)
      .then(() => {
        console.log(` 记录 ${record.recordId} 导出成功`);
        return { success: true, recordId: record.recordId };
      })
      .catch(err => {
        console.error(` 导出记录 ${record.recordId} 失败:`, err);
        return { success: false, recordId: record.recordId };
      });
  });
  Promise.all(downloads)
    .then(results => {
      const successCount = results.filter(r => r.success).length;
      if (successCount > 0) {
        proxy.$modal.msgSuccess(`成功导出 ${successCount} 个压缩包`);
      }
    })
    .finally(() => {
      exportLoading.value = false;
      exportDialogVisible.value = false;
    });
}

const { queryParams, form, rules } = toRefs(data);
// 计算属性，用于处理表格显示数据
const displayRecordList = computed(() => {
  return recordList.value.map(record => {
    // 查找任务名称
    let taskName = '未知任务';
    if (record.taskId) {
      const task = taskOptions.value.find(t => t.taskId === record.taskId);
      taskName = task ? task.taskName : `任务${record.taskId}`;
    }
    // 查找采集人名称
    let collectorName = record.collectorName || '未知用户';
    if (!record.collectorName && record.collectorId) {
      const user = userOptions.value.find(u => u.userId === record.collectorId);
      collectorName = user ? user.nickName : `用户${record.collectorId}`;
    }
    return {
      ...record,
      taskName: taskName,
      collectorName: collectorName
    };
  });
});

// 保存选中的完整记录（用于判断图片是否存在）
const selectedRecords = ref([]);

// 计算属性：判断选中记录中是否存在至少一条"有图记录"
const hasSelectValidImages = computed(() => {
  if (selectedRecords.value.length === 0) return false;
  return selectedRecords.value.some(row => getImageCount(row) > 0);
});

// 计算属性：获取选中记录中无图片的记录数量
const selectedNoImageCount = computed(() => {
  return selectedRecords.value.filter(row => getImageCount(row) === 0).length;
});

// 多选框选中数据 
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.recordId);
  selectedRecords.value = selection; // 同步保存完整选中记录
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}

// 获取图片数量 
function getImageCount(row) {
  if (!row.imageUrls) {
    return 0;
  }
  // 处理图片URL，支持数组和逗号分隔的字符串
  const imageUrls = Array.isArray(row.imageUrls) 
    ? row.imageUrls 
    : row.imageUrls.split(',').filter(url => url.trim());
  return imageUrls.length;
}

// 查询采集记录列表 
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    console.log('recordList 原始数据:', recordList.value);
    console.log('displayRecordList 处理后的数据:', displayRecordList.value);
  }).catch(error => {
    loading.value = false;
    console.error('获取记录列表失败:', error);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    recordId: null,
    taskId: null,
    collectorId: null,
    collectTime: null,
    dataValue: null,
    imageUrls: null,
    remark: null,
    createTime: null
  };
  proxy.resetForm("recordRef");
}

// 搜索按钮操作 
function handleQuery() {
  queryParams.value.pageNum = 1;
  // 根据任务名设置 taskIdList（数组） 后端 IN 查询
  if (queryParams.value.taskName) {
    queryParams.value.taskIdList = taskNameToIds.value[queryParams.value.taskName] || [];
    queryParams.value.taskId = null;
  } else {
    queryParams.value.taskIdList = null;
  }
  getList();
}

// 重置按钮操作 
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.taskName = null;
  queryParams.value.taskIdList = null;
  handleQuery();
}

// 新增按钮操作 
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加采集记录";
}

// 任务名检索所有taskID
const taskNameToIds = computed(() => {
  const map = {};
  for (const t of taskOptions.value) {
    if (!t?.taskName || t?.taskId == null) continue;
    if (!map[t.taskName]) map[t.taskName] = [];
    map[t.taskName].push(t.taskId);
  }
  return map;
});

// 去重任务名选项
const uniqueTaskNameOptions = computed(() => {
  return Object.keys(taskNameToIds.value).map(name => ({ taskName: name }));
});

// 获取任务列表 
function getTaskList() {
  listTask().then(response => {
    taskOptions.value = response.rows || [];
    console.log('任务选项:', taskOptions.value);
  });
}

// 获取用户列表 
function getUserList() {
  listUser().then(response => {
    userOptions.value = response.rows || [];
    console.log('用户选项:', userOptions.value);
  });
}

// 任务下拉框 
function getTaskLabel(task) {
  if (!task) return '';
  const labels = [];
  if (task.taskName) labels.push(task.taskName);
  // if (task.taskId) labels.push(`ID:${task.taskId}`);
  // if (task.plotName) labels.push(`地块:${task.plotName}`);
  // if (task.nickName) labels.push(`发布人:${task.nickName}`);
  return labels.join(' | ');
}

// 用户下拉框
function getUserLabel(user) {
  if (!user) return '';
  const labels = [];
  if (user.nickName) labels.push(user.nickName);
  // if (user.userName) labels.push(`账号:${user.userName}`);
  // if (user.userId) labels.push(`ID:${user.userId}`);
  // if (user.deptName) labels.push(`部门:${user.deptName}`);
  return labels.join(' | ');
}

// 修改按钮操作 
function handleUpdate(row) {
  reset();
  const _recordId = row.recordId || ids.value
  getRecord(_recordId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改采集记录";
  });
  if (taskOptions.value.length === 0) {
    getTaskList();
  }
}

// 查看全部图片 
function handleViewAllImages(row) {
  currentRecordData.value = row; // 保存当前记录数据
  if (!row.imageUrls) {
    currentImageUrls.value = [];
  } else {
    // 处理图片URL，支持数组和逗号分隔的字符串
    currentImageUrls.value = Array.isArray(row.imageUrls) 
      ? row.imageUrls 
      : row.imageUrls.split(',').filter(url => url.trim());
  }
  imageDialogVisible.value = true;
}

// 提交按钮 
function submitForm() {
  proxy.$refs["recordRef"].validate(valid => {
    if (valid) {
      if (form.value.recordId != null) {
        updateRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRecord(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

// 删除按钮操作 
function handleDelete(row) {
  const _recordIds = row.recordId || ids.value;
  proxy.$modal.confirm('是否确认删除采集记录编号为"' + _recordIds + '"的数据项？').then(function() {
    return delRecord(_recordIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

// 导出按钮 - 打开导出对话框 
function handleExport() {
  if (ids.value.length === 0) {
    proxy.$modal.msgWarning("请先选择要导出的记录");
    return;
  }
  exportForm.exportType = 'data';
  exportDialogVisible.value = true;
}

// 确认导出类型 
function confirmExport() {
  proxy.$refs["exportFormRef"].validate(valid => {
    if (valid) {
      exportForm.exportType === 'data' ? exportData() : exportImages();
    }
  });
}

// 导出数据表格 
function exportData() {
  exportLoading.value = true;
  const params = { ...queryParams.value, recordIds: ids.value.join(',') };
  proxy.download('peach/collectRecord/export', params, `record_${Date.now()}.xlsx`)
    .then(() => {
      exportDialogVisible.value = false;
    })
    .finally(() => exportLoading.value = false);
}

// 文件下载 
function handleDownload(blob, filename) {
  try {
    if (!blob) {throw new Error('Blob 对象不能为空');}
    if (!(blob instanceof Blob)) {throw new Error(`期望 Blob 类型，实际收到: ${typeof blob}`);}
    if (blob.size === 0) {throw new Error('文件内容为空，无法下载');}
    // 创建下载
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename || 'download.zip';
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    // 清理资源（延迟执行确保下载完成）
    setTimeout(() => {
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    }, 100);
  } catch (error) {
    console.error('下载文件失败:', error);
    throw error;  // 向上抛出错误，让调用者处理
  }
}

// 初始化数据
async function initData() {
  await getTaskList();
  await getUserList();
  getList();
}

// 导出图片压缩包 
// function exportImages() {
//   exportLoading.value = true;
//   const validImageRecords = selectedRecords.value
//     .filter(row => getImageCount(row) > 0);
//   if (validImageRecords.length === 0) {
//     proxy.$modal.msgWarning("选中的记录中都没有图片，无法导出");
//     exportLoading.value = false;
//     return;
//   }
//   if (selectedNoImageCount.value > 0) {
//     proxy.$modal.msgWarning(`已自动过滤 ${selectedNoImageCount.value} 条无图片记录，将导出 ${validImageRecords.length} 条有图片记录`);
//   }
//   const downloads = validImageRecords.map(record => {
//     const displayRecord = displayRecordList.value.find(r => r.recordId === record.recordId);
//     const taskName = displayRecord?.taskName || '未知任务';
//     const filename = `${taskName}_record_${record.recordId}_images.zip`;
//     return downloadRecordImgZip(record.recordId,taskName)
//       .then(blob => {
//         handleDownload(blob, filename);
//         return true;
//       })
//       .catch(err => {
//         console.error(`导出记录 ${record.recordId} 的图片失败:`, err);
//         return false;
//       });
//   });
//   Promise.all(downloads)
//     .then(results => {
//       const successCount = results.filter(result => result).length;
//       if (successCount > 0) {
//         proxy.$modal.msgSuccess(`成功导出 ${successCount} 个图片压缩包`);
//       }
//     })
//     .finally(() => {
//       exportLoading.value = false;
//       exportDialogVisible.value = false;
//     });
// }

initData();
</script>